using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using SanJ.FreeCare.EntityFrameworkCore;
using SanJ.FreeCare.ObservationDefinitions;


namespace SanJ.FreeCare.Medications
{
    public class EfCoreObservationDefinitionRepository : EfCoreObservationDefinitionRepositoryBase, IObservationDefinitionRepository
    {
        public EfCoreObservationDefinitionRepository(IDbContextProvider<FreeCareDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string filter,CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetDbSetAsync()), filter);
            return await query.LongCountAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<List<ObservationDefinition>> GetPageLisAsync(string filter,string sorting, int maxResultCount = int.MaxValue, int skipCount = 0, CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetDbSetAsync()), filter);
            query = query.OrderBy(string.IsNullOrWhiteSpace(sorting) ? MedicationConsts.GetDefaultSorting(false) : sorting);
            return await query.PageBy(skipCount, maxResultCount).ToListAsync(cancellationToken);
        }

        private IQueryable<ObservationDefinition> ApplyFilter(IQueryable<ObservationDefinition> query, string filter)
        {
            return query.WhereIf(!string.IsNullOrWhiteSpace(filter), e => e.Name.Contains(filter!) || e.Spell.Contains(filter!));
        }

 
    }
}